package pri.niddles.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pri.niddles.domain.Article;
import pri.niddles.service.IArticleService;

import java.util.List;

@Controller
@RequestMapping("/article")
public class articleController {


    @Autowired
    private IArticleService articleService;

    //查询全部文章
    @RequestMapping("/selectallarticle")
    public String selectAllArticle(Model model){
        List<Article> articles = articleService.selectAll();
        model.addAttribute("result",articles);
        return "/article/article";
    }


    //新增文章
    @RequestMapping("/addarticle")
    public String addArticle( Article article,Model model){
       System.out.println(article.toString());
        //因为前台默认是不传id的  ，所以这样我们要模拟id自增
//        Random random = new Random();
//        article.setId(random.nextInt(100));
      String okay = articleService.addArticle(article);
        if (okay == "添加成功"){
            model.addAttribute("result","成功添加");
            System.out.println("添加成功");
        }
        else {
            model.addAttribute("result","添加失败,可能是service和mapper层故障");
            System.out.println("添加失败");
        }
        return "redirect:/article/selectallarticle";
    }


    @GetMapping("/delectbyid/{id}")
    public String delectbyarticleid(@PathVariable("id") Integer id,Model model){
        String result = articleService.delectById(id);
        if (result=="success delete"){
            model.addAttribute("result","删除成功");
            return "redirect:/article/selectallarticle";
        }else {
            model.addAttribute("result","删除失败 查看service layer");
        }
        return "redirect:/article/selectallarticle";
    }

//    @GetMapping("/delectbyid")
//    public String delectbyarticleid1(Integer id,Model model){
//        String result = articleService.delectById(id);
//        if (result=="success delete"){
//            model.addAttribute("result","删除成功");
//            return "redirect:/article/selectallarticle";
//        }else {
//            model.addAttribute("result","删除失败 查看service layer");
//        }
//        return "redirect:/article/selectallarticle";
//    }


    @PostMapping("/update")
    public String updateArticle(Article article,Model model){
        String result = articleService.updateArticle(article);
        if (result == "success update"){
            model.addAttribute("result","成功更新一条数据");
        }else {
            model.addAttribute("result","更新失败 查看service layer");
        }
        return "redirect:/article/selectallarticle";
    }



}
